/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ImprimirPlanillaLlamado.java
 *
 * Created on 21-ene-2013, 15:08:52
 */
package gui.reportes;

import controladores.ControladorPrincipal;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.Printable;
import java.awt.print.PrinterJob;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.MultiplePiePlot;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.util.TableOrder;
import utilidades.JFrameConFondo;

/**
 *
 * @author NiCo
 */
public class Geografica extends JFrameConFondo implements Printable {

    private Image icono = new ImageIcon(getClass().getResource("/imagenes/logo.png")).getImage();
    private final Date finicio;
    private final Date ffin;
    private String path;

    /** Creates new form ImprimirPlanillaLlamado */
    public Geografica(Date finico, Date ffin, String titulo, List<Object[]> datos) {
        try {
            initComponents();
            JFreeChart chart = null;
            if (!titulo.equals("Zona")) {
                CategoryDataset dataset = crearDatosMultiple(datos);
                chart = crearGraficaMultiple(dataset, titulo);
            } else {
                DefaultCategoryDataset dataset = crearDatos(datos);
                chart = crearGrafica(dataset, titulo);
            }
            File archivo = new File(System.getProperty("java.io.tmpdir") + "grafica" + (ControladorPrincipal.getInstance().getGraficas() - 1) + ".png");
            archivo.delete();
            path = System.getProperty("java.io.tmpdir") + "grafica" + ControladorPrincipal.getInstance().getGraficas() + ".png";
            ChartUtilities.saveChartAsPNG(new File(path), chart, 484, 350);
            jPanelConFondo1.setImagen("");
            jPanelConFondo1.setImagen(new ImageIcon(path).getImage());
            ControladorPrincipal.getInstance().setGraficas(ControladorPrincipal.getInstance().getGraficas() + 1);
        } catch (Exception ex) {
        }
        this.finicio = finico;
        this.ffin = ffin;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnCerrar = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jPanelConFondo1 = new utilidades.JPanelConFondo();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        btnCerrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/cerrar-normal.png"))); // NOI18N
        btnCerrar.setBorder(null);
        btnCerrar.setBorderPainted(false);
        btnCerrar.setFocusPainted(false);
        btnCerrar.setName("btnCerrar"); // NOI18N
        btnCerrar.setOpaque(false);
        btnCerrar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                btnCerrarMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                btnCerrarMouseExited(evt);
            }
            public void mousePressed(java.awt.event.MouseEvent evt) {
                btnCerrarMousePressed(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                btnCerrarMouseReleased(evt);
            }
        });
        btnCerrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCerrarActionPerformed(evt);
            }
        });

        jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/titulo-estadistica-geografi.png"))); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/imprimir.png"))); // NOI18N
        jButton1.setBorderPainted(false);
        jButton1.setFocusPainted(false);
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jPanelConFondo1.setName("jPanelConFondo1"); // NOI18N

        javax.swing.GroupLayout jPanelConFondo1Layout = new javax.swing.GroupLayout(jPanelConFondo1);
        jPanelConFondo1.setLayout(jPanelConFondo1Layout);
        jPanelConFondo1Layout.setHorizontalGroup(
            jPanelConFondo1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 484, Short.MAX_VALUE)
        );
        jPanelConFondo1Layout.setVerticalGroup(
            jPanelConFondo1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 350, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(125, 125, 125)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnCerrar))
                    .addComponent(jPanelConFondo1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(182, Short.MAX_VALUE)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(180, 180, 180))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnCerrar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(11, 11, 11)
                .addComponent(jPanelConFondo1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnCerrarMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnCerrarMouseEntered

        btnCerrar.setIcon(new ImageIcon(getClass().getResource("/imagenes/cerrar-activo.png")));     }//GEN-LAST:event_btnCerrarMouseEntered

    private void btnCerrarMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnCerrarMouseExited

        btnCerrar.setIcon(new ImageIcon(getClass().getResource("/imagenes/cerrar-normal.png")));     }//GEN-LAST:event_btnCerrarMouseExited

    private void btnCerrarMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnCerrarMousePressed

        btnCerrar.setIcon(new ImageIcon(getClass().getResource("/imagenes/cerrar-click.png")));     }//GEN-LAST:event_btnCerrarMousePressed

    private void btnCerrarMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnCerrarMouseReleased

        btnCerrar.setIcon(new ImageIcon(getClass().getResource("/imagenes/cerrar-normal.png")));     }//GEN-LAST:event_btnCerrarMouseReleased

    private void btnCerrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCerrarActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnCerrarActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        PrinterJob job = PrinterJob.getPrinterJob();
        Paper hoja = new Paper();
        hoja.setImageableArea(0, 0, 595, 841);
        hoja.setSize(595, 841);
        job.setPrintable(this);
        try {
            // Diálogo para elegir el formato de impresión
            PageFormat pageFormat = new PageFormat();
            pageFormat.setPaper(hoja);
            //pageFormat = job.pageDialog(pageFormat);
            if (job.printDialog()) {
                job.print();
            }
        } catch (Exception e) {
        }

    }//GEN-LAST:event_jButton1ActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCerrar;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel2;
    private utilidades.JPanelConFondo jPanelConFondo1;
    // End of variables declaration//GEN-END:variables

    @Override
    public int print(Graphics g, PageFormat f, int pageIndex) {
        SimpleDateFormat sdf = new java.text.SimpleDateFormat("dd/MM/yyyy");
        if (pageIndex == 0) {
            try {
                // Imprime "Hola mundo" en la primera pagina, en la posicion 100,100
                Image img = ImageIO.read(new File("src/imagenes/ficha-informe-casos.png").toURI().toURL());
                g.drawImage(img, 52, 0, 491, 801, null);
            } catch (Exception ex) {
            }
            //datos del caso
            g.setFont(new Font("Tahoma", Font.BOLD, 14));
            if (ffin == null) {
                g.drawString("Fecha: " + sdf.format(finicio), 59, 152);
            } else {
                g.drawString("PERÍODO -", 59, 152);
                g.drawString("Inicio: " + sdf.format(finicio), 139, 152);
                g.drawString("Fin: " + sdf.format(ffin), 139, 171);
            }
            try {
                // Imprime "Hola mundo" en la primera pagina, en la posicion 100,100
                Image img = ImageIO.read(new File(path).toURI().toURL());
                g.drawImage(img, 59, 198, 484, 350, null);
            } catch (Exception ex) {
            }
            return PAGE_EXISTS;
        } else {
            return NO_SUCH_PAGE;
        }
    }

    private JFreeChart crearGrafica(DefaultCategoryDataset dataset, String titulo) {
        JFreeChart chart = ChartFactory.createBarChart3D(titulo, "",
                "Cant. casos", dataset, // data
                PlotOrientation.VERTICAL, true, // include legend
                true, false);
        CategoryPlot plot = (CategoryPlot) chart.getPlot();
        CategoryAxis xAxis = (CategoryAxis) plot.getDomainAxis();
        xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45); // Inclinamos 45 grados las etiquetas del eje X  
        plot.setBackgroundAlpha(0.5f);
        return chart;
    }

    private DefaultCategoryDataset crearDatos(List<Object[]> datos) {
        DefaultCategoryDataset result = new DefaultCategoryDataset();
        Iterator<Object[]> it = datos.iterator();
        while (it.hasNext()) {
            Object[] obj = it.next();
            result.setValue(Integer.parseInt(obj[1].toString()), obj[0].toString(), "");
        }

        return result;
    }

    private CategoryDataset crearDatosMultiple(List<Object[]> datos) {
        DefaultCategoryDataset result = new DefaultCategoryDataset();
        Iterator<Object[]> it = datos.iterator();
        while (it.hasNext()) {
            Object[] obj = it.next();
            result.setValue(Integer.parseInt(obj[1].toString()), obj[0].toString(), obj[2].toString());
        }
        return result;
    }

    private JFreeChart crearGraficaMultiple(CategoryDataset dataset, String titulo) {
        JFreeChart chart = ChartFactory.createMultiplePieChart3D(
                titulo, dataset, TableOrder.BY_COLUMN, true, true, false);
        MultiplePiePlot plot = (MultiplePiePlot) chart.getPlot();
        PiePlot p = (PiePlot) plot.getPieChart().getPlot();
        p.setLabelGenerator(new StandardPieSectionLabelGenerator("{1} - {2}"));
        return chart;
    }
}
